package com.yupi.yupicturespringboot.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.ciModel.job.v2.ResultInfo;
import com.qcloud.cos.utils.IOUtils;
import com.yupi.yupicturespringboot.annotation.AuthCheck;
import com.yupi.yupicturespringboot.common.BaseResponse;
import com.yupi.yupicturespringboot.common.ResultUtils;
import com.yupi.yupicturespringboot.constant.UserConstant;
import com.yupi.yupicturespringboot.exception.BusinessException;
import com.yupi.yupicturespringboot.exception.ErrorCode;
import com.yupi.yupicturespringboot.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private CosManager cosManager;

    /**
     * 测试文件上传
     *
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    public BaseResponse<String> testuploadFile(@RequestPart("file") MultipartFile file) {
        //文件目录
        String filename = file.getOriginalFilename();
        String fielpath = String.format("/test/%s", filename);
        File file1 = null;
        try {
            file1 = File.createTempFile(fielpath, null);
            file.transferTo(file1);
            cosManager.putObject(fielpath, file1);
            //返回访问的地址
            return ResultUtils.success(fielpath);
        } catch (Exception e) {
            log.error("文件上传失败,filepath:{}", fielpath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            if (file != null) {
                boolean delete = file1.delete();
                if (!delete) {
                    log.error("文件删除失败,filepath:{}", fielpath);
                }

            }
        }
    }


    /**
     * 测试文件下载
     *
     * @param filePath
     * @param response
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("test/download")
    public void testDownloadFile(String filePath, HttpServletResponse response) throws IOException{
        COSObjectInputStream cosObjectInputStream = null;
        try {
            COSObject cosObject = cosManager.getObject(filePath);
            cosObjectInputStream = cosObject.getObjectContent();
            byte[] bytes = IOUtils.toByteArray(cosObjectInputStream);
            //设置响应头
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
            //写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("文件下载失败,filepath:{}", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载失败");
        }finally {
            //释放流
            if (cosObjectInputStream!=null){
                try {
                    cosObjectInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }


}
